package com.msb.apipassenger.service;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.msb.internalcommon.constant.CommonStatusEnum;
import com.msb.internalcommon.constant.IdentityConstants;
import com.msb.internalcommon.constant.TokenTypeConstants;
import com.msb.internalcommon.dto.ResponseResult;
import com.msb.internalcommon.dto.TokenResult;
import com.msb.internalcommon.response.TokenResponse;
import com.msb.internalcommon.util.JWTUtils;
import com.msb.internalcommon.util.RedisPrefixUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Auther: WuWen
 * @Date: 2023/8/17 - 08 - 17 - 14:31
 * @Description: com.msb.apipassenger.service
 * @version: 1.0
 */
@Service
public class TokenService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    public ResponseResult refreshToken(String refreshTokenSrc) {

        // 解析refreshToken
        TokenResult refreshTokenResult = JWTUtils.checkToken(refreshTokenSrc);
        if(refreshTokenResult==null){
            return ResponseResult.fail(CommonStatusEnum.TOKEN_ERROR.getCode(),CommonStatusEnum.TOKEN_ERROR.getValue());
        }

        String phone = refreshTokenResult.getPhone();
        String identity = refreshTokenResult.getIdentity();


        // 读取redis中的refreshToken
        String refreshTokenKey = RedisPrefixUtils.generatorTokenKey(phone,identity,TokenTypeConstants.REFRESH_TOKEN);
        String refreshTokenRedis = stringRedisTemplate.opsForValue().get(refreshTokenKey);


        //判断token是否一致
        if ((!refreshTokenRedis.trim().equals(refreshTokenSrc.trim())) || StringUtils.isBlank(refreshTokenRedis)) {
            return ResponseResult.fail(CommonStatusEnum.TOKEN_ERROR.getCode(),CommonStatusEnum.TOKEN_ERROR.getValue());
        }

        // 生成新的双token
        String refreshToken = JWTUtils.generatorToken(refreshTokenKey, IdentityConstants.IDENTITY_PASSENGER, TokenTypeConstants.REFRESH_TOKEN);
        String accessTokenKey = RedisPrefixUtils.generatorTokenKey(phone, identity, IdentityConstants.IDENTITY_PASSENGER);
        String accessToken = JWTUtils.generatorToken(accessTokenKey, IdentityConstants.IDENTITY_PASSENGER, TokenTypeConstants.ACCESS_TOKEN);

        stringRedisTemplate.opsForValue().set(refreshTokenKey,refreshToken,31, TimeUnit.DAYS);
        stringRedisTemplate.opsForValue().set(accessTokenKey,accessToken,30, TimeUnit.DAYS);

        TokenResponse tokenResponse = new TokenResponse();
        tokenResponse.setRefreshToken(refreshToken);
        tokenResponse.setAccessToken(accessToken);

        return ResponseResult.success(tokenResponse);
    }


}
